#include<sys/types.h>
#include<sys/socket.h>
#include<string>
#include<cstring>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<strings.h>
#include<iostream>

enum
{
    SOCKET_ERR=1,
    BIND_ERR,
};
const int size=1024;

class UdpServer
{
    public:
        UdpServer(uint16_t port=7050,std::string ip="0.0.0.0",bool isrunning=false):port_(port),ip_(ip),isrunning_(isrunning) 
        {}
        ~UdpServer()
        {}
        void Init()
        {
            sockfd_=socket(AF_INET,SOCK_DGRAM,0);
            if(sockfd_<0)
            {
                perror("socket fail");
                exit(SOCKET_ERR);
            }
            struct sockaddr_in local;
            bzero(&local,sizeof(local));
            local.sin_family=AF_INET;
            local.sin_port=htons(port_);
            local.sin_addr.s_addr=inet_addr(ip_.c_str());

            if(bind(sockfd_,(struct sockaddr*)&local,sizeof(local))<0)
            {
                perror("bind fail");
                exit(BIND_ERR);
            }
            std::cout<<"UdpServer success socked:"<<sockfd_<<std::endl;            
        }
        void run()
        {
            isrunning_=true;
            char inbuffer[size];

            while(isrunning_)
            {
                sockaddr_in client;
                socklen_t len=sizeof(client);
    
               ssize_t n= recvfrom(sockfd_,inbuffer,sizeof(inbuffer)-1,0,(sockaddr*)&client,&len);
               if(n<0)
               {
                   perror("from fail");
                   continue;
               }
                inbuffer[n]='\0';
                std::string Info=inbuffer;
                std::string echo_string="client echo:"+Info;
                sendto(sockfd_,echo_string.c_str(),echo_string.size(),0,(const sockaddr*)&client,len);
            }
        }

    private:
        int sockfd_;
        uint16_t port_;
        std::string ip_;
        bool isrunning_;
};



